package top.kpromise.note.base;

import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import top.kpromise.common.base.BaseService;
import top.kpromise.common.base.PageResult;
import top.kpromise.note.modules.todo.entity.ToDoEntity;
import top.kpromise.note.modules.user.entity.UserEntity;
import top.kpromise.note.modules.user.service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class BaseApi {

    @Resource
    protected HttpServletRequest request;

    @Resource
    protected HttpSession session;

    @Resource
    protected HttpServletResponse response;

    @Resource
    protected UserService userService;

    public final String userName() {
        return request.getHeader("x_userName");
    }

    public final UserEntity userInfo() {
        return userService.findByUserName(userName());
    }

    public final <T> PageResult<T> list(BaseService<T> baseService, int pageSize, int pageNo) {
        return list(baseService, pageSize, pageNo, null);
    }

    public final <T> PageResult<T> list(BaseService<T> baseService, int pageSize, int pageNo, Example<T> example) {
        Page<T> result;
        if (example == null) {
            result = baseService.findAll(PageRequest.of(pageNo - 1, pageSize,
                    Sort.Direction.ASC, "orderNum"));
        } else {
            result = baseService.findAll(example, PageRequest.of(pageNo - 1, pageSize,
                    Sort.Direction.ASC, "orderNum"));
        }
        return new PageResult<T>().setResult(result);
    }
}
